package com.china08.yxyapi.api.manage.stu.mystudy.homework.dowork;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskQues;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskQues.Article;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReport;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportRepository;
import com.china08.yxyapi.service.mg.HomeworkTaskReportService;
import com.china08.yxyapi.util.DateAndLocalDateConvertUtils;
import com.china08.yxyapi.util.DateToolUtils;
import com.china08.yxyapi.util.RegexValidateUtil;

/**
 * 家长端作业系统
 * 
 * @author yangyunying
 *
 */
@CrossOrigin
@RestController
public class DoWorkFindListController extends YxyApiBaseController {

    @Autowired
    private HomeworkTaskReportRepository homeworkTaskReportRepository;

    @Autowired
    private HomeworkTaskQuesRepository homeworkTaskQuesRepository;

    @Autowired
    private HomeworkTaskReportService homeworkTaskReportService;

    /**
     * 家庭作业查询学生分页作业
     * 
     * @param reqModel
     *            请求参数
     * @param respModel
     *            响应数据
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/api_yw/manage/stu/mystudy/homework/dowork/list/srh", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Page<RespModel> precess(@RequestBody ReqModel reqModel, RespModel respModel) {

        // 排序
        Pageable pageable = reqModel.getPageable(Direction.DESC, "publishDate");
        String studentId = reqModel.studentId;

        Integer[] statusOfFinishedArr = new Integer[] { 1, 2 };
        List<Integer> statusOfFinishedLst = Arrays.asList(statusOfFinishedArr);

        // ###
        // startDate 是 2016/05/11
        Date startDate = DateToolUtils.parse(reqModel.startDate, "yyyy/MM/dd");
        String title = reqModel.title;
        String subjectName = reqModel.subjectName;
        Page<HomeworkTaskReport> page = null;

        // ###
        // 1.查页面数据开始
        page = homeworkTaskReportService.findStuTaskPageByStudentIdAndStartDateAndTitleAndSubjectName(studentId,
                startDate, title, subjectName, pageable);

        // ###
        // 2. 存放页面需要的数据
        Page<RespModel> page2 = null;
        // 返回每一页的数据存储的集合
        List<RespModel> respModelLst = new ArrayList<RespModel>();
        // 每个任务中的前三名存储的集合
        List<ThreeUserModel> preThreeUserModel = null;
        // 每个任务中前三名实体对象
        ThreeUserModel threeUserModel = null;
        // 试题实体定义变量
        HomeworkTaskQues homeworkTaskQues = null;
        // 文件对象
        List<Article> articleLst = null;
        // 文件对象模型
        List<ArticleModel> articleModelLst = null;
        // 循环中上一个家庭作业任务发布的时间 格式是 yyyy/MM/dd
        LocalDate preLocalDate = null;
        LocalDate currentLocalDate = null;
        ArticleModel articleModel = null;
        List<HomeworkTaskReport> homeworkTaskReportLst = new ArrayList<HomeworkTaskReport>();
        // ###
        // isShowPublishDate 决定页面上是否显示当前发布日期
        for (HomeworkTaskReport homeworktask : page.getContent()) {
            respModel = new RespModel();
            // 当前的localDate 日期
            currentLocalDate = DateAndLocalDateConvertUtils.asLocalDate(homeworktask.getPublishDate());
            if (preLocalDate == null) {
                respModel.isShowPublishDate = 1;
            } else {
                if (preLocalDate.isEqual(currentLocalDate)) {
                    respModel.isShowPublishDate = 0;
                } else {
                    respModel.isShowPublishDate = 1;
                }
            }
            // 把当前的localDate 赋值给 上一个localDate 变量
            preLocalDate = currentLocalDate;
            respModel.taskId = homeworktask.getTaskId();
            respModel.title = homeworktask.getTitle();
            respModel.subTitle = homeworktask.getSubTitle();
            respModel.subject = homeworktask.getSubject();
            respModel.subjectName = homeworktask.getSubjectName();
            respModel.statusOfFinished = homeworktask.getStatusOfFinished();
            respModel.notiOfFinished = homeworktask.getNotiOfFinished();
            respModel.quesOfFinished = homeworktask.getQuesOfFinished();
            respModel.publishDate = DateToolUtils.format(homeworktask.getPublishDate(), "yyyy年MM月dd日");
            respModel.predictDate = DateToolUtils.format(homeworktask.getPredictDate(), "yyyy年MM月dd日 HH:mm");
            if (LocalDateTime.now()
                    .isBefore(DateAndLocalDateConvertUtils.asLocalDateTime(homeworktask.getPredictDate()))) {// 进行中
                respModel.predictStatus = 0;
            } else {
                respModel.predictStatus = 1;
            }
            respModel.publishAnswer = homeworktask.getPublishAnswer();
            respModel.taskType = homeworktask.getTaskType();
            // 将double类型的数据保存到小数点的后两位
            DecimalFormat df = new DecimalFormat("######0.0");
            respModel.rightRate = Double.parseDouble(df.format(homeworktask.getRightRate()));
            respModel.myRanking = homeworktask.getMyRanking() == null ? 0 : homeworktask.getMyRanking();

            // ###
            // 查基础试题的数量
            respModel.quesCount = homeworktask.getQuesCount();
            // 查询前3名用于显示 (1 完成,2 批阅)
            homeworkTaskReportLst = homeworkTaskReportRepository
                    .findTop3ByTaskIdAndClassIdAndStatusOfFinishedInOrderByRightRateDesc(homeworktask.getTaskId(),
                            homeworktask.getClassId(), statusOfFinishedLst);
            preThreeUserModel = new ArrayList<ThreeUserModel>();
            for (HomeworkTaskReport homeworkTaskReport : homeworkTaskReportLst) {
                threeUserModel = new ThreeUserModel();
                threeUserModel.avatar = homeworkTaskReport.getAvatar();
                threeUserModel.studentNick = homeworkTaskReport.getStudentNick();
                preThreeUserModel.add(threeUserModel);
            }
            respModel.preThreeUser = preThreeUserModel;
            // ##
            // 通知类实体
            if (StringUtils.contains(homeworktask.getTaskType(), "0")) {// 试题作业
                respModel.quesImage = new ArrayList<String>();
                respModel.quesArticle = new ArrayList<ArticleModel>();
                respModel.ifNeedSumbit = false;
            } else {
                // 查体型是通知类题目的详细信息
                List<HomeworkTaskQues> homeworkTaskQueslst = homeworkTaskQuesRepository
                        .findByTaskIdAndQuesType(homeworktask.getTaskId(), "2");
                if (homeworkTaskQueslst == null || homeworkTaskQueslst.size() == 0) {
                    respModel.quesImage = new ArrayList<String>();
                    respModel.quesArticle = new ArrayList<ArticleModel>();
                    respModel.quesContent = null;
                    respModel.ifNeedSumbit = false;
                } else {
                    homeworkTaskQues = homeworkTaskQueslst.get(0);
                    respModel.quesImage = homeworkTaskQues.getQuesImage();
                    articleLst = homeworkTaskQues.getQuesArticle();
                    articleModelLst = new ArrayList<ArticleModel>();
                    for (Article article : articleLst) {
                        articleModel = new ArticleModel();
                        articleModel.url = article.getUrl();
                        articleModel.articleName = article.getArticle_name();
                        articleModelLst.add(articleModel);
                    }
                    respModel.quesArticle = articleModelLst;
                    respModel.quesContent = homeworkTaskQues.getQuesContent();
                    respModel.ifNeedSumbit = homeworkTaskQues.getIfNeedSumbit();
                }

            }
            respModelLst.add(respModel);
        }
        page2 = new PageImpl<RespModel>(respModelLst, pageable, page.getTotalElements());
        return page2;
    }

    protected static class ReqModel extends YxyApiPageReqModel {
        /**
         * 学生id
         */
        public String studentId;
        /**
         * 日期
         */
        public String startDate;
        /**
         * 学科名
         */
        public String subjectName;

        /**
         * 任务名称（作业名称）
         */
        public String title;

        @Override
        public void autoCheck() {
            Assert.isTrue(!"".equals(studentId) && studentId != null, "学生id未传值");
            Assert.isTrue(!"".equals(subjectName) && subjectName != null, "学科未传值");
            Assert.notNull(StringUtils.defaultIfBlank(startDate, null), "日期时间未选择");
            Assert.isTrue(RegexValidateUtil.regExpValidate(RegexValidateUtil.DATE_SLASH_REGEXP, startDate),
                    "日期格式不正确,请重新选择时间");
        }
    }

    /**
     * 前三名的用户对象实体
     *
     */
    public class ThreeUserModel {
        // 学生头像
        public String avatar;
        // 学生名昵称
        public String studentNick;
    }

    /**
     * model对象实体
     *
     */
    public class ArticleModel {
        public String url;
        public String articleName;
    }

    protected static class RespModel extends YxyApiRespModel {
        // 任务id
        public String taskId;
        // 任务名称:作业的标题
        public String title;
        // 副标题 :试题标题
        public String subTitle;
        // 学科id
        public String subject;
        // 学科名称
        public String subjectName;
        // 完成情况:-1-逾期未提交,0-未做,1-完成 ,2-已批阅,3-答题中
        public Integer statusOfFinished = 0;
        // 通知类试题状态值 0 未完成 1 已完成
        public Integer notiOfFinished;
        // 试题类状态值 0 未完成 1 已完成
        public Integer quesOfFinished;
        // 发布时间
        public String publishDate;
        // 是否显示发布时间 (0 不显示 1 是显示)
        public int isShowPublishDate;
        // 本任务截止完成时间，此时间之后就不能答题
        public String predictDate;
        // 当前任务的状态 0 进行中 1 已截止
        public Integer predictStatus;
        // 发布答案解析：0--提交作业后，1--截止时间后
        public Integer publishAnswer;
        // 正确率，在老师批改完作业之后计算，小数点后两位
        public Double rightRate;
        // 我的排名
        public Integer myRanking;
        // 试题类型 0：试题类作业，1：通知类作业 2：试题和通知类作业。
        public String taskType;
        // 试题的数量
        public Integer quesCount;
        // 前三名用户信息
        public List<ThreeUserModel> preThreeUser;
        // 通知类作业，上传的图片Url
        public List<String> quesImage;
        // 通知类作业，上传的文档,需要存储文档地址，文档的名称
        public List<ArticleModel> quesArticle;
        // 通知类作业 老师布置作业编辑的内容
        public String quesContent;
        // 通知类作业是否需要学生在线提交true需要,false不需要
        public Boolean ifNeedSumbit;
    }
}
